import React, {useState, useEffect} from "react";
import {Button, Input, Modal, notification, Pagination, Popconfirm, Select, Space, Table} from "antd";

import {fieldGet} from "../../../../common/common";
import http from "../../../../request";

import Menu from "../../../../components/Menu";
import City from "../../../../components/City";
import { store } from '../../../../store';

const { Option } = Select;
const { TextArea } = Input

const Tab3 = (props) => {
    // 楼盘id
    const {id} = props
    const field = {type: '=', level: '=', name: 'like', city: '=', region: '=', area: '='}
    // 学校-筛选-初始值
    const sForm = {
        type: undefined,
        level: undefined,
        name: '',
        city: '',
        region: '',
        area: ''
    }
    // 学校-新增-初始值
    const aForm = {
        name: '',
        city: undefined,
        region: undefined,
        area: undefined,
        address: '',
        type: undefined,
        nature: undefined,
        level: undefined,
        introduce: ''
    }
    // 附近学校-表格
    const [nearSource, setNearSource] = useState([])
    const [nearColumns] = useState([
        {
            title: '城区',
            dataIndex: 'school_data',
            key: 'school_id',
            render: text => (text.city_data?.name??'') + (text.region_data?.name??'') + (text.area_data?.name??'')
        }, {
            title: '学校名',
            dataIndex: 'school_data',
            key: 'school_id',
            render: text => text.name
        }, {
            title: '类型',
            dataIndex: 'school_data',
            key: 'school_id',
            render: text => text.type
        }, {
            title: '级别',
            dataIndex: 'school_data',
            key: 'school_id',
            render: text => text.level
        },{
            title: '性质',
            dataIndex: 'school_data',
            key: 'school_id',
            render: text => text.nature
        }, {
            title: '距离',
            dataIndex: 'distance',
            key: 'distance'
        }, {
            title: '操作',
            key: 'action',
            render: text => (
                <Space size="middle">
                    <img className="u-btn" src={require('../../../../assets/icon/icon-12.png').default} alt="" title="编辑" onClick={() => nearEdit(text.id)}/>
                    <Popconfirm title="确定删除？" okText="确定" cancelText="取消" onConfirm={() => nearDel(text.id)}>
                        <img className="u-btn" src={require('../../../../assets/icon/icon-13.png').default} alt="" title="删除"/>
                    </Popconfirm>
                </Space>
            ),
        }
    ])
    const [nearPage, setNearPage] = useState({page: 1, pageSize: 1})
    const [nearTotal, setNearTotal] = useState(0)
    // 附近学校-表格-选择
    const [nearSelectList, setNearSelectList] = useState([])
    // 附近学校-新增
    const [nearAddList, setNearAddList] = useState([])
    // 附近学校-编辑
    const [nearEditForm, setNearEditForm] = useState({})

    // 学校-城区-树状
    const [menuKeys, setMenuKeys] = useState([])
    // 学校-表格
    const [schoolForm, setSchoolForm] = useState(sForm)
    const [schoolPage, setSchoolPage] = useState({page: 1, pageSize: 1})
    const [schoolTotal, setSchoolTotal] = useState(0)
    const [schoolSource, setSchoolSource] = useState([])
    const [schoolColumns] = useState([
        {
            title: '城区',
            key: 'region',
            render: text => (text.city_data?.name??'') + (text.region_data?.name??'') + (text.area_data?.name??'')
        }, {
            title: '学校名',
            dataIndex: 'name',
            key: 'name'
        }, {
            title: '类型',
            dataIndex: 'type',
            key: 'type'
        }, {
            title: '级别',
            dataIndex: 'level',
            key: 'level'
        },{
            title: '性质',
            dataIndex: 'nature',
            key: 'nature'
        },{
            title: '楼盘数',
            dataIndex: 'id',
            key: 'id'
        }, {
            title: '操作',
            key: 'action',
            render: text => (
                <Space size="middle">
                    <img className="u-btn" src={require('../../../../assets/icon/icon-12.png').default} alt="" title="编辑" onClick={() => (!(system?.xx_xg?.value ?? 1))?setedd(!0):schoolEdit(text.id)}/>
                    <Popconfirm title="确定删除？" okText="确定" cancelText="取消" onConfirm={() =>(!(system?.xx_sc?.value ?? 1))? setedd(!0): schoolDel(text.id)}>
                        <img className="u-btn" src={require('../../../../assets/icon/icon-13.png').default} alt="" title="删除"/>
                    </Popconfirm>
                </Space>
            ),
        }
    ])
    // 学校-表格-选择
    const [schoolSelectList, setSchoolSelectList] = useState([])
    // 学校-新增-表单
    const [schoolAddForm, setSchoolAddForm] = useState(aForm)

    const [edd,setedd] = useState(!1)
    let {system} = {system:undefined}
    if(store.getState().userInfo.group_id !== 3){
        system=store.getState().staff.system
    }
    const [school, setSchool] = useState({show: !1, text: ''})
    const [batch, setBatch] = useState({show: !1, text: ''})
    const [distance, setDistance] = useState({show: !1, text: ''})

    useEffect(() => {
        nearGet()
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [nearPage])
    useEffect(() => {
        schoolGet()
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [menuKeys, schoolPage])
    return (
        <React.Fragment>
            <div className="part-title">附近学校列表</div>
            <div className="u-m-t-20">
                <Table bordered rowSelection={{
                    rowSelection: nearSelectList,
                    onChange(e){
                        setNearSelectList(e)
                    }
                }} onRow={e => ({
                    onDoubleClick: () => {
                        nearEdit(e.id)
                    }
                })} rowKey={e => e.id} scroll={{x: 1000}} size="small" dataSource={nearSource} columns={nearColumns} pagination={false} />
            </div>
            <div className="u-flex u-row-between u-m-t-20">
                <div className="u-flex">
                    <Button type="primary" size="small" onClick={batchShow}>
                        <div className="u-flex">
                            <img src={require('../../../../assets/icon/icon-18.png').default} alt=""/>
                            <span className="u-m-l-5">新增</span>
                        </div>
                    </Button>
                    <Popconfirm title="确定删除？" okText="确定" cancelText="取消" onConfirm={nearDel}>
                        <Button className="u-m-l-20" type="primary" size="small" danger>
                            <div className="u-flex">
                                <img src={require('../../../../assets/icon/icon-19.png').default} alt=""/>
                                <span className="u-m-l-5">删除</span>
                            </div>
                        </Button>
                    </Popconfirm>
                </div>
                <Pagination showQuickJumper current={nearPage.page} pageSize={nearPage.pageSize} total={nearTotal} onChange={(page,pageSize) => setNearPage({page,pageSize})} />
            </div>
            <div className="part-title u-m-t-20">学校字典</div>
            <div className="u-flex u-m-t-20">
                <div className="label">类型</div>
                <Select placeholder="类型" value={schoolForm.type} onChange={e => schoolFormChange('type', e)} className="u-m-l-10" style={{width: 120}}>
                    <Option value="学前班">学前班</Option>
                    <Option value="幼儿园">幼儿园</Option>
                    <Option value="小学">小学</Option>
                    <Option value="初中">初中</Option>
                    <Option value="高中">高中</Option>
                    <Option value="大学">大学</Option>
                </Select>
                <div className="label u-m-l-20">级别</div>
                <Select placeholder="级别" value={schoolForm.level} onChange={e => schoolFormChange('level', e)} className="u-m-l-10" style={{width: 120}}>
                    <Option value="普通">普通</Option>
                    <Option value="市重点">市重点</Option>
                    <Option value="省重点">省重点</Option>
                </Select>
                {/*<div className="label u-m-l-20">楼盘</div>*/}
                {/*<Select placeholder="楼盘" className="u-m-l-10" style={{width: 120}}>*/}
                {/*    <Option value="1">Jack</Option>*/}
                {/*</Select>*/}
                <Input placeholder="输入学校名称" value={schoolForm.name} onChange={e => schoolFormChange('name', e.target.value)} className="u-m-l-20" style={{maxWidth: 250}} />
                <Button size="mini" type="primary" onClick={schoolGet}>
                    <img src={require('../../../../assets/icon/icon-6.png').default} alt="" />
                </Button>
                <div className="u-btn u-flex u-m-l-20" onClick={schoolReset}>
                    <img src={require('../../../../assets/icon/icon-7.png').default} alt="" />
                    <span className="u-m-l-5 u-text-nowrap">清空</span>
                </div>
            </div>
            <div className="u-m-t-20 u-flex u-col-top">
                <Menu menuKeys={menuKeys} menuChange={menuChange}/>
                <Table sticky bordered rowSelection={{
                    rowSelection: schoolSelectList,
                    onChange(e){
                        setSchoolSelectList(e)
                    }
                }} onRow={e => ({
                    onDoubleClick: () => {
                        schoolEdit(e.id)
                    }
                })} rowKey={e => e.id+'-'+e.name} scroll={{x: 900}} size="small" dataSource={schoolSource} columns={schoolColumns} pagination={false} style={{width: '100%', maxHeight: 400, overflowY: 'auto'}}/>
            </div>
            <div className="u-flex u-row-between u-m-t-20">
                <div className="u-flex">
                    <Button type="primary" size="small" onClick={() => (!(system?.xx_xz?.value ?? 1))?setedd(!0):modalShow(setSchool, '加入')}>
                        <div className="u-flex">
                            <img src={require('../../../../assets/icon/icon-18.png').default} alt=""/>
                            <span className="u-m-l-5">新增</span>
                        </div>
                    </Button>
                    <Popconfirm title="确定删除？" okText="确定" cancelText="取消" onConfirm={schoolDel}>
                        <Button className="u-m-l-20" type="primary" size="small" danger>
                            <div className="u-flex">
                                <img src={require('../../../../assets/icon/icon-19.png').default} alt=""/>
                                <span className="u-m-l-5">删除</span>
                            </div>
                        </Button>
                    </Popconfirm>
                </div>
                <Pagination showQuickJumper current={schoolPage.page} pageSize={schoolPage.pageSize} total={schoolTotal} onChange={(page, pageSize) => setSchoolPage({page, pageSize})&&schoolGet()} />
            </div>
            <Modal title={school.text+"学校"} okText="保存" destroyOnClose width={450} visible={school.show} onOk={schoolAdd} onCancel={schoolAddHide}>
                <div className="Modal">
                    <div className="u-flex">
                        <div className="label">名称</div>
                        <Input placeholder="名称" value={schoolAddForm.name} onChange={e => schoolAddChange('name', e.target.value)} className="u-m-l-10" style={{width: 355}} />
                    </div>
                    <div className="u-flex u-m-t-20">
                        <div className="label">城区</div>
                        <City value={[schoolAddForm.city, schoolAddForm.region, schoolAddForm.area]} onChange={cityChange} className="u-m-l-10"/>
                    </div>
                    <div className="u-flex u-m-t-20">
                        <div className="label">地址</div>
                        <Input placeholder="地址" value={schoolAddForm.address} onChange={e => schoolAddChange('address', e.target.value)} className="u-m-l-10" style={{width: 355}} />
                    </div>
                    <div className="u-flex u-m-t-20">
                        <div className="label">类型</div>
                        <Select placeholder="类型" value={schoolAddForm.type} onChange={e => schoolAddChange('type', e)} className="u-m-l-10" style={{width: 80}}>
                            <Option value="学前班">学前班</Option>
                            <Option value="幼儿园">幼儿园</Option>
                            <Option value="小学">小学</Option>
                            <Option value="初中">初中</Option>
                            <Option value="高中">高中</Option>
                            <Option value="大学">大学</Option>
                        </Select>
                        <div className="label u-m-l-20">性质</div>
                        <Select placeholder="性质" value={schoolAddForm.nature} onChange={e => schoolAddChange('nature', e)} className="u-m-l-10" style={{width: 80}}>
                            <Option value="私立">私立</Option>
                            <Option value="公立">公立</Option>
                        </Select>
                        <div className="label u-m-l-20">级别</div>
                        <Select placeholder="级别" value={schoolAddForm.level} onChange={e => schoolAddChange('level', e)} className="u-m-l-10" style={{width: 80}}>
                            <Option value="普通">普通</Option>
                            <Option value="市重点">市重点</Option>
                            <Option value="省重点">省重点</Option>
                        </Select>
                    </div>
                    <div className="u-flex u-m-t-20">
                        <div className="label">介绍</div>
                        <TextArea placeholder="学校介绍" value={schoolAddForm.introduce} onChange={e => schoolAddChange('introduce', e.target.value)} className="u-m-l-10" style={{width: 355, height: 70}} />
                    </div>
                </div>
            </Modal>
            <Modal title="添加附近学校" okText="保存" visible={batch.show} onOk={nearAdd} onCancel={() => modalHide(setBatch)}>
                <div className="Modal">
                    <div className="u-flex">
                        <div className="label u-flex-1 u-text-center">学校</div>
                        <div className="label u-flex-1 u-text-center">距离</div>
                    </div>
                    <div style={{maxHeight: 400, overflowY: 'auto'}}>
                        {
                            nearAddList.map((batch, ind) => {
                                return (
                                    <div className="u-flex u-m-t-10" key={batch.school_id}>
                                        <div className="u-main-color u-text-center u-flex-1 u-line-1">{batch.name}</div>
                                        <div className="u-flex-1 u-text-center">
                                            <Input value={batch.distance} onChange={e => batchChange(ind, e.target.value)} style={{width: 100}} />
                                        </div>
                                    </div>
                                )
                            })
                        }
                    </div>
                </div>
            </Modal>
            <Modal title="修改距离" okText="保存" width={400} visible={distance.show} onOk={distanceConfirm} onCancel={() => modalHide(setDistance)}>
                <div className="Modal">
                    <div className="u-flex">
                        <div className="label">楼盘名称</div>
                        <div className="u-flex-1 u-main-color u-m-l-10">{nearEditForm?.estate_data?.name??''}</div>
                    </div>
                    <div className="u-flex u-m-t-10">
                        <div className="label">学校名称</div>
                        <div className="u-flex-1 u-main-color u-m-l-10">{nearEditForm?.school_data?.name??''}</div>
                    </div>
                    <div className="u-flex u-m-t-10">
                        <div className="label u-m-l-28">距离</div>
                        <Input placeholder="详细地址" value={nearEditForm.distance} onChange={distanceChange} className="u-m-l-10" style={{width: 270}} />
                    </div>
                </div>
            </Modal>
            <Modal title="提示" footer={false} visible={edd} onCancel={() => setedd(!1)}>
                <h3>权限不足</h3>
            </Modal>
        </React.Fragment>
    )
    // 附近学校-列表
    function nearGet(){
        http('near.index', {
            filter: JSON.stringify({estate_id: id}),
            op: JSON.stringify({estate_id: '='}),
            offset: (nearPage.page - 1) * nearPage.pageSize,
            limit: nearPage.pageSize
        }).then(res => {
            if(res.code === 1){
                setNearSource(res.data.rows)
                setNearTotal(res.data.total)
            }
        })
    }
    // 附近学校-添加
    function nearAdd(){
        http('near.batch', {
            row: nearAddList
        }).then(res => {
            if(res.code === 1){
                notification.success({
                    title: '提示',
                    message: res.msg || '操作成功'
                })
                nearGet()
                modalHide(setBatch)
            } else {
                notification.error({
                    title: '错误',
                    message: res.msg || '操作失败，请重试'
                })
            }
        })
    }
    // 附近学校-编辑
    function nearEdit(ids){
        http('near.one', {ids}).then(res => {
            if(res.code === 1){
                setNearEditForm(res.data)
                modalShow(setDistance)
            } else {
                notification.error({
                    message: res.msg || '错误，请重试'
                })
            }
        })
    }
    // 附近学校-删除
    function nearDel(id){
        let ids = id > 0 ? [id] : nearSelectList
        http('near.del', {ids}).then(res => {
            if(res.code === 1){
                notification.success({
                    message: res.msg || '操作成功'
                })
            } else {
                notification.error({
                    message: res.msg || '操作失败，请重试'
                })
            }
            nearGet()
        })
    }
    // 附近学校-添加-显示
    function batchShow(){
        if(schoolSelectList.length <= 0){
            notification.error({
                message: '请在字典选择中选择学校'
            })
            return 0;
        }
        setNearAddList(schoolSelectList.map(e => {
            let data = e.split('-')
            return {
                estate_id: id,
                school_id: parseInt(data[0]),
                name: data[1],
                distance: ''
            }
        }))
        modalShow(setBatch)
    }
    // 附近学校-批量新增-修改距离
    function batchChange(ind, value){
        let newList = JSON.parse(JSON.stringify(nearAddList))
        newList[ind].distance = value
        setNearAddList(newList)
    }
    // 附近学校-修改距离
    function distanceChange(e){
        let newForm = JSON.parse(JSON.stringify(nearEditForm))
        newForm.distance = e.target.value
        setNearEditForm(newForm)
    }
    // 附近学校-编辑-提交
    function distanceConfirm(){
        let form = nearEditForm
        http('near.edit', {
            row: {
                id: form.id,
                distance: form.distance
            }
        }).then(res => {
            if(res.code === 1){
                notification.success({
                    message: res.msg || '操作成功'
                })
                modalHide(setDistance)
            } else {
                notification.error({
                    message: res.msg || '操作失败'
                })
            }
            nearGet()
        })
    }
    // 学校-列表
    function schoolGet(){
        http('school.index', {
            ...fieldGet(field, schoolForm, schoolPage.page, schoolPage.pageSize),
        }).then(res => {
            if(res.code === 1){
                setSchoolSource(res.data.rows)
                setSchoolTotal(res.data.total)
            }
        })
    }
    // 学校-添加
    function schoolAdd(){
        let url = schoolAddForm?.id ? 'school.edit' : 'school.add'
        http(url, {
            row: schoolAddForm
        }).then(res => {
            if(res.code === 1){
                notification.success({
                    message: '提示',
                    description: res.msg || '操作成功',
                })
                schoolAddHide()
            } else {
                notification.error({
                    description: res.msg || '操作失败，请重试',
                })
            }
            schoolGet()
        })
    }
    // 学校-编辑
    function schoolEdit(ids){
        http('school.one', {ids}).then(res => {
            if(res.code === 1){
                setSchoolAddForm(res.data)
                modalShow(setSchool, '编辑')
            }
        })
    }
    // 学校-删除
    function schoolDel(id){
        if(!(system?.xx_sc?.value ?? 1)) return setedd(!0)
        let ids = id > 0 ? [id] : schoolSelectList.map(e => {
            return parseInt(e.split('-')[0])
        })
        http('school.del', {ids}).then(res => {
            if(res.code === 1){
                notification.success({
                    title: '提示',
                    message: res.msg || '操作成功'
                })
            } else {
                notification.error({
                    message: res.msg || '操作失败，请重试'
                })
            }
            schoolGet()
        })
    }
    function schoolFormChange(name, value){
        let newForm = JSON.parse(JSON.stringify(schoolForm))
        newForm[name] = value
        setSchoolForm(newForm)
    }
    function menuChange(id, city, region, area){
        let newForm = JSON.parse(JSON.stringify(schoolForm))
        newForm.city = city
        newForm.region = region
        newForm.area = area
        setSchoolForm(newForm)
        setMenuKeys(['city-'+id])
        schoolGet()
    }
    function schoolReset(){
        setSchoolSelectList([])
        setMenuKeys([])
        setSchoolForm(sForm)
    }
    function cityChange(city, region, area){
        let newForm = JSON.parse(JSON.stringify(schoolAddForm))
        newForm.city = city
        newForm.region = region
        newForm.area = area
        setSchoolAddForm(newForm)
    }
    function schoolAddChange(name, value){
        let newForm = JSON.parse(JSON.stringify(schoolAddForm))
        newForm[name] = value
        setSchoolAddForm(newForm)
    }
    function schoolAddHide(){
        setSchoolAddForm(aForm)
        modalHide(setSchool)
    }

    function modalShow(func, text){
        func({show: !0, text})
    }
    function modalHide(func){
        func({show: !1, text: ''})
    }
}

export default Tab3